import { httpLogin,httpUserInfo } from "@/api/login";
import {setToken,getToken,removeToken} from "@/utils/auth";
export default{
  namespaced: true,
  state: {
    token:getToken() ?? null,
    userInfo:JSON.parse(window.localStorage.getItem('userInfo')) ?? {},
  },
  getters: {},
  mutations: {
    SER_TOKEN(state,token){
      state.token = token
    },
    SET_INFO(state,payload){
      state.userInfo = payload
    },
    REMOVE_USER(state){
      removeToken()
      window.localStorage.removeItem('userInfo')
      state.token = null
      state.userInfo = {}
    }
  },
  actions: {
    async login({commit},payload){
      let res = await httpLogin(payload)
      let info
      if(res.success){
        setToken(res.data)
        commit('SER_TOKEN',res.data)
         info = await httpUserInfo()
         window.localStorage.setItem('userInfo',JSON.stringify(info.data))
         commit('SET_INFO',info.data)

      }
      return info
    },
    logout({commit}){
      commit('REMOVE_USER')
    }
  }
}
